package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbDict;
import com.bwie.service.TbDictService;
import com.bwie.mapper.TbDictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
* @author andy
* @description 针对表【tb_dict(字典表)】的数据库操作Service实现
* @createDate 2025-03-25 14:18:56
*/
@Service
public class TbDictServiceImpl extends ServiceImpl<TbDictMapper, TbDict>
    implements TbDictService{

    @Autowired
    TbDictMapper tbDictMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * @description 项目启动时，从数据库中读取字典数据，到缓存中
     * @params []
     * @return void
     * @author 军哥
     * @date 2025/3/25 14:26
     */
    @PostConstruct
    public void loadDict() {
        // 增量更新
        System.out.println("加载字典数据到缓存中");

        List<TbDict> tbDicts = tbDictMapper.selectList(null);

        // redis hash存储
        // dict -> id -> object
        String key = "dict";
        for (TbDict tbDict : tbDicts) {
            Boolean hasKey = stringRedisTemplate.opsForHash().hasKey(key, tbDict.getDictId().toString());
            if(!hasKey) {
                stringRedisTemplate.opsForHash().put(key, tbDict.getDictId().toString(), JSON.toJSONString(tbDict));
            }
        }

        // 全量更新
//        List<TbDict> tbDicts = tbDictMapper.selectList(null);
//        stringRedisTemplate.opsForValue().set("dict", JSON.toJSONString(tbDicts));
    }

}




